<?php
declare (strict_types = 1);

namespace uctoo\middleware;

use think\facade\Config;
use think\Request;
use think\Response;

class CORS
{


    /**
     * header头
     * @var array
     */
    protected $header = [
        'Access-Control-Allow-Headers'  => 'Authorization, Content-Type, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since, X-Requested-With',
        'Access-Control-Allow-Methods'  => 'GET,POST,PATCH,PUT,DELETE,OPTIONS,DELETE',
        'Access-Control-Max-Age'        =>  '1728000'
    ];



    /**
     * @param Request $request
     * @param \Closure $next
     * @return Response
     */
    public function handle(Request $request, \Closure $next)
    {
        $cookieDomain = array_filter(explode(',',Config::get('cookie.domain', '')));
        
        $origin = $request->header('origin');
        if(!$cookieDomain){
            $this->header['Access-Control-Allow-Origin'] = '*';
        }
        if (in_array($origin,$cookieDomain)){
            $this->header['Access-Control-Allow-Origin'] = $origin;
        }

        if ('OPTIONS' == $request->method(true)) {
            $response = Response::create('ok')->code(200)->header($this->header);
        } else {
            $response = $next($request)->header($this->header);
        }

        return $response;
    }

}
